/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare",
    "scprit/followup/app/datatable/datatable.servers.js",
    "scprit/followup/app/datatable/datatable.ui.js",
     "scprit/imgCollection/app/equipmentManagement/equipmentManagement.ui.js"],
    function($,$bb,$datatableServers,$datatableUi,$ui){
	var servers = {};
	var URL = $bb.baseUrl("imgCollection");
    var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
    /**
     * 入参
     */
    var inParams = function(args){
        var data = JSON.stringify({
            data: {
                "args": JSON.stringify(args),
                "classId": $.trim($('#selectOptions').val()),
                "equipAlias": $.trim($('#equipNumber').val()),
                "programId": $.trim($('#procedureNumber').val())
            }
        });
        return data;
    }
    /**
     * 出参
     */
    var outParams = function(data){
        return data.rows;
    };
    /**
     * columns
     */
    var status = function(e){
        return e.flag ? "正常" : "异常";
    }
    var columnsData = function(e){
        var columnsArr = ['className','equipAlias','programId',status,null];
        return $datatableServers.getColumnsData(columnsArr);
    };
    /*
    * 行回调：
    * */
    var rowCallback = function(row, data, index){
        var html = "<a>修改</a>";
        $('td:last()',row).html(html);
        $('td:last() a', row).click(function(){
            var equipTypeFn = function(dt){
                data.rows = dt.data.rows;
                data.title = "修改设备";
                $ui.modifyEquipInit({"id":"#modalBox","data":data});
                $('#myModal').modal({backdrop: "static",keyboard:false,show:true});
                $('#myModal').off("click","button[flag=0]");
                $('#myModal').on("click","button[flag=0]",function(){
                    confirmation();
                    var params = paramsDefine();
                    var paramsCallFn = function(data){
                        $('#myModal').modal('hide');
                        $bb.toastShow("修改成功",1500);
                        $datatableUi.table.api().ajax.reload(null,false);
                    };
                    servers.modifyEquip(params,paramsCallFn);
                });
            };
            servers.getEquipType(equipTypeFn);
        })
    };
    /**
     * 初始化完成之后的回调函数
     */
    var initComplete = function(setting,json){
        $("#equipment").prev("div.row").children().first().removeClass("col-xs-6").addClass("col-xs-12");
        $("#equipment").prev("div.row").children().last().remove();
        var h = '<div id="search" class="search">'+
            '<label>设备类型：'+
                '    <span id="searchType"></span>'+
            '</label>'+
            '<label>设备编号：'+
            '    <input id="equipNumber" type="text" class="form-control input-sm">'+
            '</label>'+
            '<label>程序编号：'+
            '    <input id="procedureNumber" type="text" class="form-control input-sm">'+
            '</label>'+
            '<label>'+
            '   <button id="toSearch" class="btn btn-info">查询</button>'+
            '   <button id="reset" type="reset" class="btn btn-default">重置</button>'+
            '</label>'+
            '</div>';
        $("#equipment").prev("div.row").children().first().prepend(h);
        var equipTypeFn = function(dt) {
            $ui.drawSelectOptions({"id":"#searchType","data":dt.data.rows});
        };
        servers.getEquipType(equipTypeFn);
        $("#toSearch").bind("click",function(){
            $datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
        });
        $("#reset").bind("click",function(){
            $("#search input").each(function(index,val){
                $(this).val("");
            });
            var value = $("#searchType select").val();
            $("#searchType").find('option[value="'+ value +'"]').removeAttr("selected");
            $("#searchType").find('option[value=""]').attr("selected",true);
            $datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
        });
    };
    /**
     * 获取datatable里的options
     */
    servers.getOptions = function(){
        var sessionId = $bb.getSessionStorage("sessionId");
        var options = {
            "ajax": {
                "url": URL + "imgCollection/setting/equipManage/queryEquip?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams
            },
            "columns": columnsData(),
            "rowCallback":rowCallback,
            "initComplete": initComplete
        };
        return options;
    };
    /*
    * 修改设备：
    **/
    servers.modifyEquip  = function(params,callback){
        $bb.ajax({
            url: URL + "imgCollection/setting/equipManage/modifyEquip",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }else{
                    /*if(data.code.indexOf("4004") >= 0){
                        $bb.toastShow(data.msg,1500);
                    }*/
                    $bb.toastShow(data.msg,1500);
                }
            }
        });
    };
    /*
    * 添加设备：
    * */
    servers.addEquip  = function(params,callback){
        $bb.ajax({
            url: URL + "imgCollection/setting/equipManage/addNewEquip",
            data: JSON.stringify({
                data: params
            }),
            success: function (data) {
                if(data.success){
                    callback(data);
                }else{
                    /*if(data.code.indexOf("4004") >= 0){
                        $bb.toastShow(data.msg,1500);
                    }*/
                    $bb.toastShow(data.msg,1500);
                }
            }
        });
    };
    /*
     * 获取设备类型：
     * */
    servers.getEquipType  = function(callback){
        $bb.ajax({
            url: URL + "imgCollection/setting/equipManage/queryEquipClass",
            success: function (data) {
                if(data.success){
                    callback(data);
                }
            }
        });
    };
    /*
    * 添加设备按钮：
    * */
    servers.addBtn = function(){
        var addFn = function(){
            var equipTypeFn = function(dt){
                $ui.modifyEquipInit({"id":"#modalBox","data":{"title":"添加设备","rows":dt.data.rows}});
                $('#myModal').modal({backdrop: "static",keyboard:false,show:true});
                $('#myModal').off("click","button[flag=0]");
                $('#myModal').on("click","button[flag=0]",function(){
                    confirmation();
                    var params = paramsDefine();
                    var paramsCallFn = function(data){
                        $('#myModal').modal('hide');
                        $bb.toastShow("添加成功",1500);
                        $datatableUi.table.api().ajax.reload();
                    };
                    servers.addEquip(params,paramsCallFn);
                });
            };
            servers.getEquipType(equipTypeFn);
        };
        var topbars = [
            {
                "icon":"fa fa-plus",
                "name":"添加设备",
                "callback":addFn
            }
        ];
        $bb.toolbar(topbars);
    };
    /*
    * “确定”按钮：
    * */
    var paramsDefine = function(){
        var equipId = $("#equipId").attr("equipId");
        var opCode = equipId ? "2011":"2010";
        var change = equipId ? "修改":"添加";
        var opType = "3";
        var opNote="医生【 "+sessinonName+"】"+change+"设备编号为"+$.trim($("#modify-equipNumber").val())+"的设备";
        var params = {
            "equipInfo":{
                "classId":$.trim($("#modify-equipType").val()),
                "equipAlias":$.trim($("#modify-equipNumber").val()),
                "programId":$.trim($("#modify-procedureNumber").val()),
                "equipDesc":$.trim($("#modify-equipDesc").val())
            },
            "oprInfo":{
                "opCode":opCode,
                "opNote":opNote,
                "opType":opType
            }
        };
        if(equipId){params.equipInfo.equipId = equipId;}
        return params;
    };
    /*
    * 验证：
    * */
    var confirmation = function(){
        var arr = ["modify-equipType","modify-equipNumber","modify-procedureNumber"];
        for(var i = 0;i<arr.length;i++){
            if(!$.trim($("#"+arr[i]).val())){
                var id = arr[i];
                var type = id == "modify-equipType" ? "设备类型" : id == "modify-equipNumber" ? "设备编号":"程序编号";
                var tips = type + "不能为空";
                $bb.toastShow(tips,1500);
                return;
            }
        }
    };
	return servers;
});